<?php
// +----------------------------------------------------------------------
// | QSCMS
// +----------------------------------------------------------------------
// | Copyright (c)  2025 https://www.qqss.net All rights reserved.
// +----------------------------------------------------------------------
// | Licensed QSCMS is not free software, commercial use must purchase official license from official website to avoid unnecessary legal disputes.
// +----------------------------------------------------------------------
// | Author: Contract 990504246@qq.com
// +----------------------------------------------------------------------

namespace app\service\translation;

use app\common\model\TranslateApi;
use app\service\translation\providers\BaiduTranslateProvider;
use app\service\translation\providers\GoogleTranslateProvider;
use app\service\translation\providers\DeepLTranslateProvider;
use app\service\translation\providers\OpenAITranslateProvider;

/**
 * 翻译API服务类
 */
class TranslateApiService
{
    private $lastUsedProvider = null;

    /**
     * 翻译文本
     */
    public function translate($text, $targetLanguage, $sourceLanguage = 'zh_CN')
    {
        if (empty($text)) {
            return '';
        }

        // 如果目标语言和源语言相同，直接返回
        if ($targetLanguage === $sourceLanguage) {
            return $text;
        }

        // 获取可用的API
        $api = TranslateApi::getAvailableApi();
        if (!$api) {
            throw new \Exception('没有可用的翻译API');
        }

        // 获取翻译提供商
        $provider = $this->getProvider($api);
        if (!$provider) {
            throw new \Exception('不支持的翻译提供商: ' . $api->provider);
        }

        try {
            // 执行翻译
            $result = $provider->translate($text, $targetLanguage, $sourceLanguage);

            // 增加API使用次数
            $api->incrementUsage();

            // 记录使用的提供商
            $this->lastUsedProvider = $api->provider;

            return $result;

        } catch (\Exception $e) {
            throw new \Exception("翻译失败 ({$api->provider}): " . $e->getMessage());
        }
    }

    /**
     * 批量翻译
     */
    public function batchTranslate($texts, $targetLanguage, $sourceLanguage = 'zh_CN')
    {
        $results = [];

        foreach ($texts as $key => $text) {
            try {
                $results[$key] = $this->translate($text, $targetLanguage, $sourceLanguage);
            } catch (\Exception $e) {
                $results[$key] = $text; // 翻译失败时返回原文
                error_log("Batch translate failed for key {$key}: " . $e->getMessage());
            }
        }

        return $results;
    }

    /**
     * 获取翻译提供商实例
     */
    private function getProvider(TranslateApi $api)
    {
        $config = $api->getApiConfig();

        switch ($api->provider) {
            case 'baidu':
                return new BaiduTranslateProvider($config);
            case 'google':
                return new GoogleTranslateProvider($config);
            case 'deepl':
                return new DeepLTranslateProvider($config);
            case 'openai':
                return new OpenAITranslateProvider($config);
            default:
                return null;
        }
    }

    /**
     * 检测语言
     */
    public function detectLanguage($text)
    {
        $api = TranslateApi::getAvailableApi();
        if (!$api) {
            return 'zh_CN'; // 默认返回中文
        }

        $provider = $this->getProvider($api);
        if (!$provider || !method_exists($provider, 'detectLanguage')) {
            return 'zh_CN';
        }

        try {
            return $provider->detectLanguage($text);
        } catch (\Exception $e) {
            return 'zh_CN';
        }
    }

    /**
     * 获取支持的语言列表
     */
    public function getSupportedLanguages($provider = null)
    {
        if (!$provider) {
            $api      = TranslateApi::getAvailableApi();
            $provider = $api ? $api->provider : 'baidu';
        }

        $languageMap = [
            'baidu'  => [
                'zh_CN' => 'zh',
                'en_US' => 'en',
                'ja_JP' => 'jp',
                'ko_KR' => 'kor',
                'fr_FR' => 'fra',
                'de_DE' => 'de',
                'es_ES' => 'spa',
                'pt_PT' => 'pt',
                'ru_RU' => 'ru',
                'ar_SA' => 'ara',
            ],
            'google' => [
                'zh_CN' => 'zh-cn',
                'en_US' => 'en',
                'ja_JP' => 'ja',
                'ko_KR' => 'ko',
                'fr_FR' => 'fr',
                'de_DE' => 'de',
                'es_ES' => 'es',
                'pt_PT' => 'pt',
                'ru_RU' => 'ru',
                'ar_SA' => 'ar',
            ],
            'deepl'  => [
                'zh_CN' => 'ZH',
                'en_US' => 'EN-US',
                'ja_JP' => 'JA',
                'ko_KR' => 'KO',
                'fr_FR' => 'FR',
                'de_DE' => 'DE',
                'es_ES' => 'ES',
                'pt_PT' => 'PT-PT',
                'ru_RU' => 'RU',
            ],
        ];

        return $languageMap[$provider] ?? $languageMap['baidu'];
    }

    /**
     * 转换语言代码
     */
    public function convertLanguageCode($languageCode, $provider)
    {
        $supportedLanguages = $this->getSupportedLanguages($provider);
        return $supportedLanguages[$languageCode] ?? $languageCode;
    }

    /**
     * 获取最后使用的提供商
     */
    public function getLastUsedProvider()
    {
        return $this->lastUsedProvider;
    }

    /**
     * 测试API连接
     */
    public function testApiConnection($apiId)
    {
        $api = TranslateApi::find($apiId);
        if (!$api) {
            return ['success' => false, 'message' => 'API配置不存在'];
        }

        $provider = $this->getProvider($api);
        if (!$provider) {
            return ['success' => false, 'message' => '不支持的翻译提供商'];
        }

        try {
            $result = $provider->translate('测试', 'en', 'zh');
            return [
                'success' => true,
                'message' => 'API连接正常',
                'result'  => $result
            ];
        } catch (\Exception $e) {
            return [
                'success' => false,
                'message' => 'API连接失败: ' . $e->getMessage()
            ];
        }
    }

    /**
     * 获取API使用统计
     */
    public function getApiUsageStats()
    {
        $apis  = TranslateApi::getEnabledApis();
        $stats = [];

        foreach ($apis as $api) {
            $stats[] = [
                'name'         => $api->name,
                'provider'     => $api->provider,
                'daily_used'   => $api->daily_used,
                'daily_limit'  => $api->daily_limit,
                'usage_rate'   => $api->daily_limit > 0
                    ? round($api->daily_used / $api->daily_limit * 100, 2)
                    : 0,
                'is_available' => $api->isAvailable(),
            ];
        }

        return $stats;
    }
}
